<?php

namespace app\admin\controller;

use think\Request;
use think\Validate;

class Category extends Base
{
    // 分类首页
    public function index(){
        // 获取数据表中的所有数据
        $arrs = \app\admin\model\Category::select();
        // 实例化模型对象
        $category = new \app\admin\model\Category();
        // 定义变量接受 模型中创建的方法，
        $data = $category->categoryList($arrs);

        return view('category/index',['data'=>$data]);
    }

    // 添加分类
    public function add()
    {
        $arrs = \app\admin\model\Category::select();

        $cargate = new \app\admin\model\Category();

        $data = $cargate->categoryList($arrs);
        return view("add",['data'=>$data]);
    }

    // 添加分类到数据库
    public function save(Request $request){

        $data = $request->param();

        $rule = [
            'classname|名称' => "require",
            'orderby|排序' => "require"
        ];

        $validate = new \think\Validate($rule);
        if(!$validate->check($data)){
            $error = $validate->getError();
            return $this->error($error);
        }

        \app\admin\model\Category::create($data,true);

        $this->success("添加成功","index");
    }

    // 修改分类
    public function edit(int $id){

        if(empty($id)){
            return $this->error("非法字符",'admin/category/index');
        }

        $data = \app\admin\model\Category::where('id',$id)->find();

        // 无线级分类
        $arrs = \app\admin\model\Category::select();

        $catrgory = new \app\admin\model\Category();

        $List = $catrgory->categoryList($arrs);

        return view('/category/edit',['data'=>$data,'List'=>$List]);

    }

    public function update(Request $request,int $id)
    {
       $data = $request->param();

       if(empty($id)){
           return $this->error("非法字符",'admin/category/index');
       }

       $res = \app\admin\model\Category::where('id' ,$id)->strict(false)->update($data);
       dump($res);

       return $this->success("修改成功",'admin/category/index');
    }


    public function delete(int $id)
    {
        if(empty($id)){
            $this->error("您输入的不正确",'admin/category/index');
        }
        \app\admin\model\Category::destroy($id);
        $this->success("删除成功",'admin/category/index');
    }
}
